import { request } from 'umi';
import { TenantEntity, TenantEntityFormat } from './entities';
import { CREATE, DELETE, UPDATE, LIST } from '@/constant';

const route = '/tenant';

export async function getTenantOptions() {
  return await request<OptionEntity[]>(`${route}/get_tenant_options`, {
    method: 'GET',
  });
}

export async function getFormatTenant(id: string) {
  return new Promise<TenantEntityFormat>((resolve, reject) => {
    getTenant(id).then((data) => {
      const { allow_nodes } = data;
      const result = {
        ...data,
        allow_nodes: allow_nodes.split(',')
      };
      resolve(result)
    }).catch((e) => {
      reject(e)
    })
  })
}

export async function getTenant(id: string) {
  return await request<TenantEntity>(`${route}/get_entity?id=${id}`, {
    method: 'GET',
  });
}

export async function listTenant(params: {
  current?: number;
  pageSize?: number;
}, options?: { [key: string]: any }) {
  return request<{
    data: TenantEntity[];
    total?: number;
    success?: boolean
  }>(`${route}${LIST}`, {
    method: 'GET',
    params: {
      ...params,
    },
    ...options,
  });
}

export async function addTenant(data: { [key: string]: any }, options?: { [key: string]: any }) {
  return request<Record<string, any>>(`${route}${CREATE}`, {
    data,
    method: 'POST',
    ...(options || {}),
  });
}

export async function updateTenant(data: { [key: string]: any }, options?: { [key: string]: any }) {
  return request<Record<string, any>>(`${route}${UPDATE}`, {
    data,
    method: 'POST',
    ...(options || {}),
  });
}

export async function deleteTenant(data: string, options?: { key: string[] }) {
  return request<Record<string, any>>(`${route}${DELETE}?ids=${data}`, {
    method: 'GET',
    ...(options || {}),
  });
}
